<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace app\commands;

use app\award\Award;
use app\models\admin_ops\AdminOpsRefill;
use app\models\order\Order;
use app\models\pay\Pay;
use app\models\Queue;
use app\models\Transfer;
use app\models\user\User;
use app\models\user\UserAccount;
use app\models\user\UserCash;
use app\models\user\UserCommission;
use app\models\user\UserConsume;
use app\util\Request;
use app\util\Util;
use yii\console\Controller;
use yii\console\ExitCode;
use yii\helpers\ArrayHelper;

/**
 * This command echoes the first argument that you have entered.
 *
 * This command is provided as an example for you to learn how to create console commands.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class HelloController extends Controller
{
    /**
     * This command echoes what you have entered as the message.
     * @param string $message the message to be echoed.
     * @return int Exit code
     */
    public function actionIndex($message = 'hello world')
    {
        echo $message . "\n";

        return ExitCode::OK;
    }

    public function actionTest()
    {
        // $str = '{"r1_MerchantNo":"888111400005329","r2_OrderNo":"2021091616072176206","r3_Amount":"0.01","r4_Cur":"1","r5_Mp":"","r6_Status":"100","r7_TrxNo":"100221091669681357","r8_BankOrderNo":"100221091669681357","r9_BankTrxNo":"4200001210202109160871166467","ra_PayTime":"2021-09-16+16%3A07%3A29","rb_DealTime":"2021-09-16+16%3A07%3A29","rc_BankCode":"WEIXIN_GZH","hmac":"2d74f5f0076ac9ed21d0ad73c02dca2f"}';
        $str = '{"r1_MerchantNo":"888111400005329","r2_OrderNo":"2021091616371482755","r3_Amount":"0.01","r4_Cur":"1","r5_Mp":"","r6_Status":"100","r7_TrxNo":"100221091669705106","r8_BankOrderNo":"100221091669705106","r9_BankTrxNo":"4200001216202109163834555478","ra_PayTime":"2021-09-16+16%3A37%3A24","rb_DealTime":"2021-09-16+16%3A37%3A24","rc_BankCode":"WEIXIN_GZH","hmac":"273ae461ecf68d9a16030100fb57c70f"}';
        $arr = json_decode($str, true);
        $hmac = $arr['hmac'];

        $sign = 'fe2069d412d34894afdc83235d1b3181';

        // 2d74f5f0076ac9ed21d0ad73c02dca2f
        // 273ae461ecf68d9a16030100fb57c70f
        // ksort($arr);
        unset($arr['hmac']);
        $x = $this->signature($arr);
        $x = md5($x . $sign);

        var_dump($x, $hmac);

    }

    public function signature($params)
    {
        $str = '';
        foreach ($params as $param) {
            $str .= $param;
        }

        return $str;
    }

    public function actionGo()
    {
        // $url = 'https://www.chinaz.com/2022/0623/1411615.shtml';
        $url = 'http://m.titan007.com';
        $response = Request::get($url);
        var_dump($response);
    }

    public function actionY()
    {
        $url = 'http://yxsq.tydiy.com/web/reg/index.html?recommend=';
        for ($i = 0; $i < 99999; $i++) {
            $url .= $i;
            $res = Request::get($url);
            var_dump($res);
        }
    }

    public function actionSms()
    {
        $url = 'http://yxsq.tydiy.com/api/user/sendSms';
        $data = [
            // 'phone' => '18661652747',
            'phone' => '15913198695',
            'area_code' => '86',
        ];

        for ($i = 0; $i < 99999; $i++) {
            $res = Request::post($url, $data);
            var_dump($res);
        }
    }

    public function actionReg()
    {
        $url = 'http://yxsq.tydiy.com/api/user/register';
        $data = [
            'account' => '18661652747',
            'code' => '123456',
            'password' => '123456',
            'password_confirmation' => '123456',
            'recommend' => 'Y9TUCN',
        ];

        for ($i = 0; $i < 99999; $i++) {
            $res = Request::post($url, $data);
            var_dump($res);
        }
    }

    // 佣金
    public function _user($id)
    {
        // $id = 11417;
        // $id = 11812;
        // $id = 11236;
        // $id = 11427;
        // $id = 11297;

        $commission = (float)UserCommission::find()
            ->where(['user_id' => $id])
            ->andWhere(['status' => 1])
            ->sum('balance');

        $refill = (float)AdminOpsRefill::find()
            ->where(['user_id' => $id])
            ->sum('balance');

        // $send = (float)Transfer::find()
        //     ->where(['send_id' => $id])
        //     ->sum('amount');
        //
        // $received = (float)Transfer::find()
        //     ->where(['received_id' => $id])
        //     ->sum('amount');

        // $consume = (float)UserConsume::find()
        //     ->where(['user_id' => $id])
        //     ->sum('balance');

        $consume = (float)Order::find()
            ->where(['user_id' => $id])
            ->andWhere(['!=', 'status', Order::$statusMapping['NON_PAYMENT']])
            ->andWhere(['!=', 'status', Order::$statusMapping['CANCEL']])
            ->andWhere(['!=', 'status', Order::$statusMapping['DELETE']])
            ->andWhere(['!=', 'status', Order::$statusMapping['REFUND']])
            ->sum('use_balance');

        $cash = (float)UserCash::find()
            ->where(['user_id' => $id])
            ->andWhere(['status' => 1])
            ->sum('amount');

        $account = (float)UserAccount::find()
            ->where(['user_id' => $id])
            ->sum('balance');

        // var_dump($commission, $refill, $consume, $send, $received, $cash);
        // var_dump($account);

        // $consume = 5990;

        // 现金
        // $pay = Pay::find()
        //     ->where(['user_id' => $id])
        //     ->andWhere(['status' => 1])
        //     ->sum('amount');

        // 退款[现金]
        $refund = (float)Order::find()
            ->where(['user_id' => $id])
            ->andWhere(['=', 'status', Order::$statusMapping['REFUND']])
            ->sum('use_money');

        // $str = "ID: {$id}, 佣金: {$commission}, 充值: {$refill}, 消费: {$consume}, 发送: {$send}, 接收: {$received}, 提现: {$cash}";
        $str = "ID: {$id}, 佣金: {$commission}, 充值: {$refill}, 消费: {$consume}, 提现: {$cash}, 退款: {$refund}";

        // $result = $commission + $refill + $received - $consume - $send - $cash;
        $result = $commission + $refill - $consume - $cash + $refund;
        $result = round($result, 2);

        // if ($send > 0 || $received > 0) {
        //     echo $id, "\n";
        // }
        //
        // return ;

        echo $str;
        echo "\n 应该剩下余额: {$result}, 实际余额: {$account} \n";

        if ($result != $account) {
        // if ($account - $result > 1) {
        // if ($result - $account > 0.01) {
        //     echo $str;
        //     echo "\n 应该剩下余额: {$result}, 实际余额: {$account} \n";

            // 修正
            $a = UserAccount::findOne(['user_id' => $id]);
            $a->balance = $result;
            $a->save();

        }

        return ExitCode::OK;
    }


    public function actionUser()
    {
        $list = User::find()
            // ->where(['id' => 11213])
            ->all();

        foreach ($list as $user) {
            // echo "ID => {$user->id} \n";
            $this->_user($user->id);
        }
    }

    // 佣金去重[返了两次的]
    public function actionCommissionReset()
    {
        $ids = Order::find()
            ->select(['id'])
            ->column();

        foreach ($ids as $id) {
            echo $id, "\n";
            $commissions = UserCommission::find()
                ->where(['order_id' => $id])
                ->all();

            $list = [];
            foreach ($commissions as $c) {
                // $cc = "{$c->order_id}-{$c->user_id}-{$c->balance}-{$c->award_type}-{$c->status}";
                $cc = "{$c->order_id}-{$c->user_id}-{$c->award_type}-{$c->status}";
                if (in_array($cc, $list)) {
                    // var_dump($cc);exit;
                    // 删除
                    $c->delete();
                } else {
                    array_push($list, $cc);
                }

            }
        }
    }


    public function actionAccountAwait()
    {
        $user = User::find()
            ->all();

        foreach ($user as $u) {
            $a = UserAccount::findOne(['user_id' => $u->id]);
            $await = (float)UserCommission::find()
                ->where(['status' => 0])
                ->andWhere(['user_id' => $u->id])
                ->sum('balance');
            if ($a->await_balance != $await) {
                echo $u->id, "\n";
                $a->await_balance = $await;
                $a->save();
            }
        }
    }

    public function actionQuery()
    {
        $user_id = 11213;

        $commissions = UserCommission::find()
            ->where(['user_id' => $user_id])
            ->andWhere(['status' => 1])
            ->all();

        $list = [];
        foreach ($commissions as $c) {
            // $cc = "{$c->order_id}-{$c->user_id}-{$c->balance}-{$c->award_type}-{$c->status}";
            $cc = "{$c->order_id}-{$c->user_id}-{$c->award_type}-{$c->status}--{$c->balance}";
            if (in_array($cc, $list)) {
                var_dump($cc);
                // 删除
                // $c->delete();
            } else {
                array_push($list, $cc);
            }

        }
    }

    public function actionDiv()
    {
        // set_time_limit(60 * 60 * 24);

        // 从哪条开始
        $last_id = Queue::find()
            ->orderBy(['id' => SORT_DESC])
            ->limit(1)
            ->select(['order_id'])
            ->scalar();
        if (!$last_id) {
            $last_id = 818;
        }

        // 计算上周的时间范围
        $now = time();
        $monday = strtotime('monday this week', $now); // 本周一
        $lastWeekStart = $monday - 7 * 24 * 3600; // 上周一开始
        $lastWeekEnd = $monday - 1; // 上周日结束

        // 格式化为日期字符串
        $lastWeekStartStr = date('Y-m-d H:i:s', $lastWeekStart);
        $lastWeekEndStr = date('Y-m-d H:i:s', $lastWeekEnd);

        $orders = Order::find()
            ->where(['>=', 'id', $last_id + 1])
            ->andWhere(['>=', 'create_time', $lastWeekStartStr])
            ->andWhere(['<=', 'create_time', $lastWeekEndStr])
            ->andWhere(['!=', 'status', Order::$statusMapping['NON_PAYMENT']])
            ->andWhere(['!=', 'status', Order::$statusMapping['CANCEL']])
            ->andWhere(['!=', 'status', Order::$statusMapping['DELETE']])
            ->andWhere(['!=', 'status', Order::$statusMapping['REFUND']])
            ->orderBy(['id' => SORT_ASC])
            // 每次操作一条
            // ->limit(1)
            ->all();

        // var_dump(ArrayHelper::getColumn($orders, 'total_price'));exit;

        $transaction = \Yii::$app->db->beginTransaction();
        try {
            foreach ($orders as $order) {

                // var_dump($order);exit;

                // 是否已经返了
                $has = UserCommission::find()
                    ->where(['order_id' => $order->id])
                    ->andWhere(['award_type' => 5])
                    ->one();
                if ($has) {
                    continue;
                }

                new Award($order, false, true);

                $log = new Queue();
                $log->order_id = $order->id;
                $log->save();

                echo $order->id, " ... ok \n";
            }

            $transaction->commit();

        } catch (\Exception $e) {
            $transaction->rollBack();
        }

    }
}
